package com.victor.controller.mobile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.History;
import com.victor.entity.PictureStatic;
import com.victor.entity.Statistics;
import com.victor.service.HistoryService;
import com.victor.service.PictureStaticService;
import com.victor.service.PicturebookService;
import com.victor.service.StatisticsService;
import com.victor.utils.Msg;

/**
 * 历史记录controller
 * 
 * @author Administrator
 */
@RestController
@RequestMapping("/history")
public class HistoryController {

	@Autowired
	private HistoryService service;

	@Autowired
	private PictureStaticService staticService;

	@Autowired
	private StatisticsService sService;

	@Autowired
	private PlatformTransactionManager txManager;
	
	@Autowired
	private PicturebookService picService;
	
	/**
	 * 历史记录
	 * 
	 * @param uid
	 * @return
	 */
	@GetMapping("/getHistory/{pictype}/{uid}")
	public Msg getHistory(@PathVariable("uid") String uid, @PathVariable("pictype") String pictype) {
		List<Map<String, String>> list = service.getHistorym(uid, null);
		List<Map<String, String>> historyList = list.stream().limit(3L).collect(Collectors.toList());
		return Msg.success().add("history", historyList);
	}

	/**
	 * 历史记录 - 更多
	 * 
	 * @param uid
	 * @param pictype
	 * @return
	 */
	@GetMapping("/getHistory/{pictype}/{uid}/more")
	public Msg getHistoryMore(@PathVariable("uid") String uid, @PathVariable("pictype") String pictype) {
		List<Map<String, String>> list = service.getHistorym(uid, pictype);
		return Msg.success().add("history", list);
	}

	/**
	 * 新增历史信息
	 * 
	 * @param history
	 * @return
	 * @throws ParseException
	 */
	@PostMapping("/insert")
	public Msg insert(History history) {
		History picList = service.findByPicId(history.getHPicId(), history.getHUserId());
		boolean bool = false;
		if (picList != null) {
			history.setHId(picList.getHId());
			bool = service.updatePicId(history);
			if (!bool) {
				return Msg.fail("修改历史记录失败");
			}
		} else {
			bool = service.insert(history);
			if (!bool) {
				return Msg.fail("新增历史记录失败");
			}
		}

		// 新增绘本状态
		PictureStatic p = new PictureStatic();
		p.setSUserId(history.getHUserId());
		p.setSPicId(history.getHPicId());
		p.setSIsYD("1");
		bool = staticService.insert(p);
		if (!bool) {
			return Msg.fail("新增绘本状态失败");
		}

		return Msg.success();
	}

	/**
	 * 修改历史信息
	 * 
	 * @param history
	 * @return
	 */
	@PostMapping("/update")
	public Msg update(History history) {
		// 手动开启事物
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			boolean bool = picService.addClick(history.getHPicId());
			if (!bool) {
				txManager.rollback(status);
				return Msg.fail("修改历史记录失败");
			}
			History findByPicId = service.findByPicId(history.getHPicId(), history.getHUserId());
			if (findByPicId == null) {
				txManager.rollback(status);
				return Msg.fail("没有本书的历史记录");
			}
			history.setHId(findByPicId.getHId());
			bool = service.update(history);
			if (!bool) {
				txManager.rollback(status);
				return Msg.fail("修改历史记录失败");
			}
			if (findByPicId.getHEndTime() == null || findByPicId.getHEndTime().isEmpty()) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Statistics s = sService.findByParam(history.getHPicId(), history.getHUserId(),
						history.getHEndTime().substring(0, 10));
				if (s == null) {
					s = new Statistics();
					s.setSUserId(history.getHUserId());
					s.setSPicId(history.getHPicId());
					s.setSPicType(findByPicId.getHPicType());
					s.setSTime(history.getHEndTime().substring(0, 10));
					Instant start = sdf.parse(findByPicId.getHTime()).toInstant();
					Instant end = sdf.parse(history.getHEndTime()).toInstant();
					long minutes = Duration.between(start, end).toMinutes();
					s.setSLength(String.valueOf(minutes));
					bool = sService.insert(s);
					if (!bool) {
						txManager.rollback(status);
						return Msg.fail("新增统计信息失败");
					}
				} else {
					Instant start = sdf.parse(findByPicId.getHTime()).toInstant();
					Instant end = sdf.parse(history.getHEndTime()).toInstant();
					long minutes = Duration.between(start, end).toMinutes() + Long.valueOf(s.getSLength());
					s.setSLength(String.valueOf(minutes));
					bool = sService.update(s);
					if (!bool) {
						txManager.rollback(status);
						return Msg.fail("修改统计信息失败");
					}
				}
			}
		} catch (Exception e) {
			txManager.rollback(status);
			e.printStackTrace();
			return Msg.fail(e.getMessage());
		}
		txManager.commit(status);
		return Msg.success();
	}

	/**
	 * 删除历史信息
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("/batchDelete")
	public Msg batchDelete(int[] ids) {
		boolean bool = service.batchDelete(ids);
		return Msg.judge(bool);
	}

}
